package com.monica.speaker;

import android.util.Log;

public class L {
    private static final int D = 0;
    private static final int V = 1;
    private static final int I = 2;
    private static final int W = 3;
    private static final int E = 4;

    public static void d(String tag, String... values) {
        printf(D, tag, values);
    }

    public static void v(String tag, String... values) {
        printf(V, tag, values);
    }

    public static void i(String tag, String... values) {
        printf(I, tag, values);
    }

    public static void w(String tag, String... values) {
        printf(W, tag, values);
    }

    public static void e(String tag, String... values) {
        printf(E, tag, values);
    }

    private static void printf(int mark, String tag, String... values) {
        StringBuffer value = new StringBuffer();
        for (int i = 0; i < values.length; i++) {
            value.append(values[i]);
            if (i == values.length - 1) {
                break;
            }
            value.append(", ");
        }
        printfLine(mark, tag, value.toString());
    }

    private static String getPosition(String tag) {
        StringBuilder sb = new StringBuilder();
        StackTraceElement element = getTargetStack(tag);

        if (null == element) {
            return null;
        }
        sb.append("(")
                .append(element.getFileName())
                .append(":")
                .append(element.getLineNumber())
                .append(")");
        return sb.toString();
    }

    private static void printfLine(int mark, String tag, String msg) {
        String startLine = getPosition(tag) + "-<thread:" + Thread.currentThread().getName() + ">-{" + msg + "}";
        switch (mark) {
            case D:
                Log.d(tag, startLine);
                break;
            case V:
                Log.v(tag, startLine);
                break;
            case I:
                Log.i(tag, startLine);
                break;
            case W:
                Log.w(tag, startLine);
                break;
            case E:
                Log.e(tag, startLine);
                break;
        }
    }

    private static StackTraceElement getTargetStack(String tag) {
        for (StackTraceElement element : Thread.currentThread().getStackTrace()) {
            if (element.getClassName().contains(tag)) {
                //返回调用位置的 element
                return element;
            }
        }
        return null;
    }
}